<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
        </div>
      </template>
      <el-row class="row-bg" justify="space-between">
        <el-col :span="4">
          <el-input
            v-model="pageData.search"
            placeholder="来源标识/学生/家长/老师/手机号/卡号"
            clearable
            class="height40"
            style="width: 400px"
            @clear="searchInfo"
          >
            <template #append>
              <el-button @click="searchInfo">搜索</el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12">
          <div class="right">
            <el-button
              type="primary"
              class="height40"
              @click="onClickBatchDistribution"
              >批量分配</el-button
            >
            <el-button type="primary" class="height40" @click="adduserdate"
              >创建用户</el-button
            >
            <el-button
              type="primary"
              class="height40"
              @click="onClickUserListExport"
              >导出execl</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-form :inline="true" :model="pageData" class="margintop">
        <el-form-item style="width: 110px">
          <!-- popper-options 解决控制台警告 -->
          <el-select
            :popper-options="{
              modifiers: [
                { name: 'computeStyles', options: { adaptive: false } },
              ],
            }"
            v-model="pageData.graduate_time"
            placeholder="高考年份"
            clearable
            class="height40"
            @change="searchInfo"
          >
            <el-option
              v-for="item in gaoKaoYear"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 110px">
          <el-select
            :popper-options="{
              modifiers: [
                { name: 'computeStyles', options: { adaptive: false } },
              ],
            }"
            v-model="pageData.course"
            placeholder="科目"
            clearable
            class="height40"
            @change="searchInfo"
          >
            <el-option
              v-for="item in subject"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 110px">
          <el-select
            :popper-options="{
              modifiers: [
                { name: 'computeStyles', options: { adaptive: false } },
              ],
            }"
            v-model="pageData.pid"
            placeholder="省份"
            clearable
            class="height40"
            @change="searchInfo"
          >
            <el-option
              v-for="item in province"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 110px">
          <el-select
            :popper-options="{
              modifiers: [
                { name: 'computeStyles', options: { adaptive: false } },
              ],
            }"
            v-model="pageData.formType"
            placeholder="设备"
            clearable
            class="height40"
            @change="searchInfo"
          >
            <el-option
              v-for="item in facility"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 110px">
          <el-select
            :popper-options="{
              modifiers: [
                { name: 'computeStyles', options: { adaptive: false } },
              ],
            }"
            v-model="pageData.type"
            placeholder="用户类型"
            clearable
            class="height40"
            @change="searchInfo"
          >
            <el-option
              v-for="item in usertype"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          style="width: 320px; margin-bottom: 10px"
          class="height40"
        >
          <el-date-picker
            clearable
            v-model="value1"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="search"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="成绩:" class="height40" style="margin-left: 10px">
          <el-input
            style="width: 110px; margin-bottom: 15px"
            v-model="pageData.minScore"
            clearable
            placeholder="最低分"
          />
          <div style="margin-bottom: 15px">&nbsp;-&nbsp;</div>
          <el-input
            style="width: 110px; margin-bottom: 15px"
            v-model="pageData.maxScore"
            clearable
            placeholder="最高分"
          />
        </el-form-item>
        <el-form-item class="height40" style="margin-bottom: 10px">
          <el-button type="primary" @click="searchInfo()">筛选</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        style="width: 100%"
        class="margintop"
        @selection-change="handleSelectionChange"
        v-loading="isRequest"
        :header-cell-style="{ 'border-bottom': 'none' }"
        :header-row-style="{ height: '60px' }"
        :cell-style="{ height: '60px', 'border-bottom': 'none' }"
        stripe
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="phone" label="手机号" width="130" align="center">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="lookUserChange(scope.row)"
            >
              {{ scope.row.phone }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="nick"
          label="学生姓名"
          width="100"
          align="center"
        />
        <el-table-column prop="graduate_time" label="高考年份" align="center" />
        <el-table-column prop="course" label="科目" align="center" />
        <el-table-column prop="province" label="省份" align="center" />
        <el-table-column prop="result" label="成绩" width="200" align="center">
          <template #default="scope">
            <span> {{ scope.row.score }}分{{ scope.row.sgname }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="teacher" label="老师" align="center" />
        <el-table-column prop="evaluationCount" label="报告" align="center">
          <template #default="scope">
            <div class="curr" @click="handleReport(scope)">
              {{ scope.row.evaluationCount }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="device" label="设备" width="150">
					<template #default="scope">
						<span>
							{{ scope.row.device ? scope.row.device : "暂不支持" }}
						</span>
					</template>
				</el-table-column> -->
        <!-- <el-table-column prop="fromType" label="来源标识">
					<template #default="scope">
						<span>
							{{ scope.row.fromType ? scope.row.fromType : "暂不支持" }}
						</span>
					</template>
				</el-table-column> -->
        <el-table-column prop="userType" label="用户类型" align="center">
          <template #default="scope">
            <span>
              {{ userTypeChange(scope.row) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="userType"
          label="VIP激活模式"
          width="100"
          align="center"
        >
          <template #default="scope">
            <span>
              {{ vipTypeChange(scope.row) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="create_time"
          label="注册时间"
          width="200"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="开通志愿卡"
              placement="top"
            >
              <el-image
                style="width: 20px; height: 20px"
                :src="icon0"
                @click="openCardChange(scope.row, 0)"
              />
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="开通升学卡"
              placement="top"
              style="margin: 0 10px"
            >
              <el-image
                style="width: 20px; height: 20px; margin: 0 5px"
                :src="icon1"
                @click="openCardChange(scope.row, 1)"
              />
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="重置"
              placement="top"
            >
              <el-icon
                size="20"
                style="cursor: pointer"
                @click="resetChange(scope.row)"
              >
                <RefreshRight />
              </el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="right" style="margin-top: 20px">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="pageData.page"
            v-model:page-size="pageData.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total"
            @size-change="pagination"
            @current-change="pagination"
          />
        </el-config-provider>
      </div>
    </el-card>
    <resetInfo ref="reset"></resetInfo>
    <openCard ref="open" @refreshUserList="searchInfo"></openCard>
    <updateUser
      :province="province"
      :gaoKaoYear="gaoKaoYear"
      ref="update"
      @refreshUserList="searchInfo"
    >
    </updateUser>
    <!-- 批量分配 -->
    <batchDistribution
      ref="batchDistributionRef"
      :isUserList="true"
      :teacherArr="teacherArr"
      :selStudentArr="selStudentArr"
      @refreshList="searchInfo"
    ></batchDistribution>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import resetInfo from './module/resetInfo.vue';
import openCard from './module/openCard.vue';
import updateUser from './module/upadateUser.vue';
import batchDistribution from '@/views/leader/Filling/module/batchDistribution.vue';
import { ElMessage } from 'element-plus';
import icon0 from '@/assets/icons/icon0.png';
import icon1 from '@/assets/icons/icon1.png';
import {
  userList,
  userListFilter,
  userListExport,
} from '@/api/manage/manage.js';
import { accountList } from '@/api/system/account.js';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import { useRouter } from 'vue-router';
const router = useRouter();

const batchDistributionRef = ref(null);
const value1 = ref('');
const reset = ref();
const open = ref();
const update = ref();
const tableData = ref([]);
const pageData = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
});
const gaoKaoYear = ref([]); // 高考年份
const subject = ref([]); // 科目
const province = ref([]); // 省份
const facility = ref([]); // 省份
const usertype = ref([]); // 类型
const vip_price = ref(''); // 抵扣费
const isRequest = ref(false); // 是否在请求

const teacherArr = ref([]); // 老师数组
const selStudentArr = ref([]); // 选中学生数组
const user_password = ref(''); // 重制密码

initSource();

function initSource() {
  userSearch();
  getlistChange();
  getAccountList();
}

function adduserdate() {
  update.value.openChange();
}

// 导出用户列表
function onClickUserListExport() {
  userListExport(pageData).then((res) => {
    window.location.href = res.data.url;
    ElMessage.success('导出成功');
  });
}

const handleReport = (rowData) => {
  localStorage.setItem('student_id', rowData.row.id);
  let localStorageData = {
    score: rowData.row.score,
    section: rowData.row.section,
    sgname: rowData.row.sgname,
    batch: rowData.row.batch,
  };
  localStorage.setItem('student_data', JSON.stringify(localStorageData));

  if (rowData.row.evaluationCount) {
    router.push({
      path: '/leader/majorRecommend',
      query: {
        sgid: rowData.row.sgid,
      },
    });
  } else {
    return;
  }
};

function userTypeChange(val) {
  if (val.type === 0) return '普通用户';
  if (val.type === 1) return '志愿卡';
  if (val.type === 2) return '升学卡';
  if (val.type === 3) return '体验卡';
}

function vipTypeChange(val) {
  if (val.vip_pay_type === 0) return '普通用户';
  if (val.vip_pay_type === 1) return '用户绑卡';
  if (val.vip_pay_type === 2) return '后端绑卡';
  if (val.vip_pay_type === 3) return '在线购买';
}

function searchInfo() {
  pageData.page = 1;
  getlistChange(); // 刷新当前数据信息
}

function search(val) {
  if (val) {
    pageData.createStartTime = val[0];
    pageData.createEndTime = val[1];
  } else {
    pageData.createStartTime = '';
    pageData.createEndTime = '';
  }
  getlistChange();
}

function userSearch() {
  userListFilter().then((res) => {
    if (res.code === 20000) {
      gaoKaoYear.value = res.data[0].data;
      subject.value = res.data[1].data;
      province.value = res.data[2].data;
      facility.value = res.data[3].data;
      usertype.value = res.data[4].data;
      vip_price.value = res.data.vip_price;
      user_password.value = res.data.user_password;
    }
  });
}

function getlistChange() {
  Object.keys(pageData).forEach(function (key) {
    if (pageData[key] === '') {
      delete pageData[key];
    }
  });

  isRequest.value = true;
  userList(pageData)
    .then((res) => {
      isRequest.value = false;
      tableData.value = res.data.data;
      pageData.total = res.data.total;
    })
    .catch(() => {
      isRequest.value = false;
    });
}

// 获取老师列表
function getAccountList() {
  accountList({
    pageSize: 100,
  }).then((res) => {
    teacherArr.value = res.data.data;
  });
}

// 学生勾选数据改变
function handleSelectionChange(val) {
  selStudentArr.value = val;
}

// 批量分配
function onClickBatchDistribution() {
  if (selStudentArr.value.length == 0) {
    ElMessage({
      message: '请选择需要分配的学生',
      type: 'warning',
    });
    return;
  }
  batchDistributionRef.value.openChange();
}

function pagination() {
  getlistChange(); // 切换加载数据
}

function lookUserChange(val) {
  update.value.openChange(val);
}

function openCardChange(val, idx) {
  val.teacherId = JSON.parse(localStorage.getItem('userDateInfo')).id;
  open.value.openChange(val, idx, vip_price.value);
}

function resetChange(val) {
  reset.value.openChange(
    {
      ...val,
    },
    user_password.value
  );
}
</script>
<style lang="scss" scoped>
::v-deep(.el-form--inline .el-form-item) {
  margin-right: 7px;
}

::v-deep(.el-form-item--default) {
  margin-bottom: 4px;
}

.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 5px;
  }
}
</style>
